<template>
	<el-container>
		<el-header>
			<div class="left-panel">
				<el-button v-auth="'SysTaskJob.Create'" type="primary" icon="el-icon-plus" @click="add"></el-button>
				<el-button v-auth="'SysTaskJob.Delete'" type="danger" plain icon="el-icon-delete" :disabled="selection.length==0" @click="batch_del"></el-button>
				<span>&nbsp;&nbsp;下次刷新 {{ refershValue }} 秒</span>
			</div>
			<div class="right-panel">
				<div class="right-panel-search">
					<el-input v-model="search.id" placeholder="ID" clearable></el-input>
					<el-input v-model="search.name" placeholder="名称" clearable></el-input>
					<el-input v-model="search.groupName" placeholder="分组" clearable></el-input>
					<el-button type="primary" icon="el-icon-search" @click="upsearch"></el-button>
					<el-button type="warning" icon="el-icon-circle-close" @click="upclear"></el-button>
				</div>
			</div>
		</el-header>
		<el-main class="nopadding">
			<scTable ref="table" :apiObj="apiObj" row-key="id" @selection-change="selectionChange" stripe>
				<el-table-column type="selection" width="50"></el-table-column>
                <el-table-column label="ID" prop="id"></el-table-column>
                <el-table-column label="任务名称" prop="name" min-width="210" show-overflow-tooltip>
					<template #default="scope">
						<el-link v-if="scope.row.name && scope.row.name.length > 0" @click="
						$router.push({
							path: '/sys/task/log/list',
							query: { name: scope.row.name }
						})">{{ scope.row.name }}</el-link>
						<span v-else>未加载，需要更新或重启后端服务</span>
					</template>
				</el-table-column>
                <el-table-column label="任务分组" prop="groupName" min-width="150" show-overflow-tooltip>
					<template #default="scope">
						<el-link @click="searchGroup(scope.row, scope.$index)">{{ scope.row.groupName }}</el-link>
					</template>
				</el-table-column>
                <el-table-column label="状态" prop="status" width="60">
					<template #default="scope">			
						<span v-if="scope.row.status=='ENABLED'" plain size="small" text>
							<sc-status-indicator type="success"></sc-status-indicator> 启用
						</span>
						<span v-if="scope.row.status=='DISABLED'" plain size="small" text>
							<sc-status-indicator type="danger"></sc-status-indicator> 禁用
						</span>
						<span v-if="scope.row.status=='PAUSED'" plain size="small" text>
							<sc-status-indicator type="warning"></sc-status-indicator> 暂停
						</span>
					</template>
				</el-table-column>
                <el-table-column label="运行状态" prop="runStatus" width="75">
					<template #default="scope">									
						<span v-if="scope.row.runStatus=='SUCCESS'" plain size="small" text>
							<sc-status-indicator type="success"></sc-status-indicator> 成功
						</span>
						<span v-if="scope.row.runStatus=='READY'" plain size="small" text>
							<sc-status-indicator type="primary"></sc-status-indicator> 等待中
						</span>
						<span v-if="scope.row.runStatus=='RUNNING'" plain size="small" text>
							<sc-status-indicator type="warning"></sc-status-indicator> 运行中
						</span>
						<span v-if="scope.row.runStatus=='ABNORMAL'" plain size="small" text>
							<sc-status-indicator type="info"></sc-status-indicator>
							<el-popover
								placement="top"
								title="任务状态信息"
								trigger="hover"
								width="350"
								content="任务完成，但部分内容异常，详见任务执行日志">
								<template v-slot:reference>
									完成
								</template>
							</el-popover>
						</span>
						<span v-if="scope.row.runStatus=='FAILED'" plain size="small" text>
							<sc-status-indicator type="danger"></sc-status-indicator>
							<el-popover
								placement="top"
								title="失败信息"
								trigger="hover"
								width="350"
								:content="scope.row.runRemarks">
								<template v-slot:reference>
									失败
								</template>
							</el-popover>
						</span>
					</template>
				</el-table-column>
                <!-- <el-table-column label="执行器: CLASS: | EXEC: | BEAN: | GET: | POST:" prop="actuator"></el-table-column> -->
                <el-table-column label="触发规则" prop="schedule" width="120">
					<template #default="scope">
						<el-link @click="table_times(scope.row, scope.$index)">{{scope.row.schedule}}</el-link>
					</template>
				</el-table-column>
                <!-- <el-table-column label="触发异常规则: NOW | NEXT" prop="instruction"></el-table-column> -->
                <!-- <el-table-column label="参数列表" prop="param"></el-table-column> -->
                <!-- <el-table-column label="运行描述" prop="runRemarks"></el-table-column> -->
                <!-- <el-table-column label="最后运行开始时间" prop="runTimeStart"></el-table-column> -->
                <!-- <el-table-column label="最后运行结束时间" prop="runTimeEnd"></el-table-column> -->
                <el-table-column :label="`下次执行(`+this.$CONFIG.DATE_TIME_ZONE_TEXT+`)`" prop="nextTime" width="150">
					<template #default="scope">{{ this.$TOOL.dateFormat(scope.row.nextTime) }}</template>
				</el-table-column>
                <el-table-column :label="`装载时间(`+this.$CONFIG.DATE_TIME_ZONE_TEXT+`)`" prop="loadTime" width="150">
					<template #default="scope">{{ this.$TOOL.dateFormat(scope.row.loadTime) }}</template>
				</el-table-column>
                <el-table-column :label="`开始时间(`+this.$CONFIG.DATE_TIME_ZONE_TEXT+`)`" prop="startTime" width="150">
					<template #default="scope">{{ this.$TOOL.dateFormat(scope.row.startTime) }}</template>
				</el-table-column>
                <el-table-column :label="`终止时间(`+this.$CONFIG.DATE_TIME_ZONE_TEXT+`)`" prop="expireTime" width="150">
					<template #default="scope">{{ this.$TOOL.dateFormat(scope.row.expireTime) }}</template>
				</el-table-column>
                <el-table-column label="运行主机" prop="hostname">
					<template #default="scope">{{ scope.row.hostname ?? '-' }}</template>
				</el-table-column>
                <el-table-column label="运行环境" prop="envName">
					<template #default="scope">{{ scope.row.envName ?? '-' }}</template>
				</el-table-column>
                <el-table-column label="描述" prop="description" width="200" show-overflow-tooltip></el-table-column>
                <!-- <el-table-column :label="`创建时间(`+this.$CONFIG.DATE_TIME_ZONE_TEXT+`)`" prop="createTime" width="190"></el-table-column> -->
				<el-table-column label="操作" fixed="right" align="right" width="215">
					<template #default="scope">
						<el-button-group>
							<el-button text v-auth="'SysTaskJob.Read'" type="primary" size="small" @click="run_show(scope.row, scope.$index)" icon="el-icon-video-play" v-if="!(scope.row.runStatus=='RUNNING')">运行</el-button>
							<el-button text v-auth="'SysTaskJob.Read'" type="primary" size="small" @click="run_stop(scope.row, scope.$index)" icon="el-icon-close" v-if="scope.row.runStatus=='RUNNING'">停止</el-button>
							<el-button text v-auth="'SysTaskJob.Update'" type="primary" size="small" @click="table_disable(scope.row, 1)" icon="el-icon-video-pause" v-if="scope.row.status=='ENABLED'">禁用</el-button>
							<el-button text v-auth="'SysTaskJob.Update'" type="primary" size="small" @click="table_disable(scope.row, 0)" icon="el-icon-refresh-right" v-if="scope.row.status=='DISABLED'">启用</el-button>
							<el-button text v-auth="'SysTaskJob.Read'" type="primary" size="small" @click="show_log(scope.row, scope.$index)" icon="el-icon-document">日志</el-button>
							<el-button text v-auth="'SysTaskJob.Read'" type="primary" size="small" @click="table_show(scope.row, scope.$index)">查看</el-button>
							<el-button text v-auth="'SysTaskJob.Update'" type="primary" size="small" @click="table_edit(scope.row, scope.$index)">编辑</el-button>
							<el-popconfirm title="确定删除吗？" @confirm="table_del(scope.row, scope.$index)">
								<template #reference>
									<el-button v-auth="'SysTaskJob.Delete'" text type="primary" size="small">删除</el-button>
								</template>
							</el-popconfirm>
						</el-button-group>
					</template>
				</el-table-column>
			</scTable>
		</el-main>
	</el-container>

	<save-dialog v-if="dialog.save" ref="saveDialog" @success="handleSaveSuccess" @closed="dialog.save=false"></save-dialog>

	<run-dialog v-if="dialog.run" ref="runDialog" @success="runSaveSuccess" @closed="dialog.run=false"></run-dialog>

	<el-dialog v-model="dialog.log" :title="logDialogTitle" width="75%" custom-class="logDialog">
		<div>1. 以下展示任务近期执行日志，可能包含多次执行，请注意区分。</div>
		<div>2. 单次执行日志请查看执行记录。</div>
		<div><el-checkbox v-model="logDialogAutoLoad">自动加载</el-checkbox> <el-checkbox v-model="logDialogAutoScoll">自动滚动</el-checkbox></div>
		<div>&nbsp;</div>
		<pre style="white-space: pre-wrap;" v-for="(item, index) in logDialogData" :key="index">{{ item }}</pre>
	</el-dialog>
	
	<el-dialog v-model="dialog.schedule" :title="scheduleDialogTitle">
		<div class="scheduleList" v-if="scheduleList.length > 0">
			<div class="scheduleListItem" v-for="(item, i) in scheduleList" :key="i">{{ item }}</div>
		</div>
		<div class="scheduleList" v-if="scheduleList.length == 0">
			<div class="scheduleListItem">未配置规则或规则配置错误</div>
		</div>
	</el-dialog>

</template>


<script>
	import saveDialog from './save'
	import runDialog from './run'
	import setting from './setting'

	export default {
		name: 'role',
		components: {
			saveDialog,
			runDialog
		},
		data() {
			return {
				dialog: {
					save: false,
					run: false,
					log: false,
					schedule: false
				},
				apiObj: setting.api.list,
				selection: [],
				search: {
					id: null,
					name: null
				},
				refershValue: 15,
				refershTimer: '',
				scheduleList: ["loading..."],
				scheduleDialogTitle: '执行时间表',
				lastLogIndex: 0,
				logDialogTimer: null,
				logDialogTitle: "TASK LOG",
				logDialogData: [],
				logDialogName: '',
				logDialogAutoLoad: true,
				logDialogAutoScoll: true
			}
		},
		mounted() {
			this.refershTimer = setInterval(this.refersh,1000)
			this.logDialogTimer = setInterval(this.refersh_log, 3500)
		},
		unmounted() {
			clearInterval(this.refershTimer);
			clearInterval(this.logDialogTimer);
		},
		methods: {
			//刷新
			refersh(){
				this.refershValue --
				if (this.refershValue < 1) {
					this.$refs.table.refresh()
					this.refershValue = 15
				}
			},
			//添加
			add(){
				this.dialog.save = true
				this.$nextTick(() => {
					this.$refs.saveDialog.open()
				})
			},
			//编辑
			table_edit(row){
				this.dialog.save = true
				this.$nextTick(() => {
					this.$refs.saveDialog.open('edit').setData(row)
				})
			},
			//查看
			table_show(row){
				this.dialog.save = true
				this.$nextTick(() => {
					this.$refs.saveDialog.open('show').setData(row)
				})
			},
			//显示日志
			async show_log(row) {
				this.dialog.log = true
				this.lastLogIndex = 0
				this.logDialogName = row.name
				this.logDialogTitle = row.name + " 日志"
				this.logDialogData = ['loading...']
				//
				var res = await setting.api.log.get({
					name: row.name,
					lastIndex: this.lastLogIndex
				});
				if(res.code == setting.successCode){
					this.logDialogLoading = false
					if (res.data.length > 0) {						
						this.logDialogData = [];
						for(let i=0;i<res.data.length;i++){
							this.lastLogIndex = res.data[i].index
							this.logDialogData.push(res.data[i].content)
						}
					} else {
						this.logDialogData = ['no content']
					}
				}else{
					this.$alert(res.message, "提示", {type: 'error'})
				}
			},
			//时间
			async table_times(row){
				this.dialog.schedule = true;
				this.scheduleDialogTitle = '任务"' + row.name + '"执行时间表';
				this.scheduleList= ["loading..."];
				var res = await setting.api.times.get({
					name: row.name,
					size: 20
				});
				if(res.code == setting.successCode){
					this.scheduleList = res.data;
				}else{
					this.$alert(res.message, "提示", {type: 'error'})
				}
			},
			//刷新日志
			async refersh_log() {
				if (!this.dialog.log) {
					return;
				}
				if (!this.logDialogAutoLoad) {
					return;
				}
				//
				var res = await setting.api.log.get({
					name: this.logDialogName,
					lastIndex: this.lastLogIndex
				});
				if(res.code == setting.successCode){
					if (res.data.length > 0) {		
						for(let i=0;i<res.data.length;i++){
							this.lastLogIndex = res.data[i].index
							this.logDialogData.push(res.data[i].content)
						}
						// scroll bottom
						if (this.logDialogAutoScoll) {
							setTimeout(() => {
								let container = document.getElementsByClassName('logDialog')[0].parentElement;
								container.scrollTop = container.querySelector('.el-dialog').scrollHeight;
								container.scrollIntoView({ behavior: 'smooth', block: 'end' })
							}, 100);
						}
					}
				}
			},
			//删除
			table_del(row){
				this.table_del_ids(row.id)
			},
			async table_del_ids(ids){
				const loading = this.$loading();
				var reqData = {ids: ids}
				var res = await setting.api.del.post(reqData);
				if(res.code == setting.successCode){
					this.$refs.table.refresh()
					this.$message.success("成功删除"+ res.data +"条数据")
				}else{
					this.$alert(res.message, "提示", {type: 'error'})
				}
				loading.close();
			},
			//批量删除
			async batch_del(){
			    this.$confirm('确定删除选中的 '+ this.selection.length +' 项吗？如果删除项中含有子集将会被一并删除', '提示', {
					type: 'warning'
				}).then(() => {
					const ids = this.selection.map(item=>item.id).join(',')
					this.table_del_ids(ids)
				}).catch(() => {

				})
			},
			//弹出运行面板
			run_show(row){
				this.dialog.run = true
				this.$nextTick(() => {
					this.$refs.runDialog.open().setData(row)
				})
			},
			async table_disable(row,val){
				const loading = this.$loading();
				var reqData = {name: row.name,value: val}
				var res = await setting.api.disable.post(reqData);
				if(res.code == setting.successCode){
					this.$refs.table.refresh()
					this.$message.success("操作成功")
				}else{
					this.$alert(res.message, "提示", {type: 'error'})
				}
				loading.close();
			},
			//停止运行
			async run_stop(row){
				const loading = this.$loading();
				var reqData = {name: row.name}
				var res = await setting.api.stop.post(reqData);
				if(res.code == setting.successCode){
					this.$refs.table.refresh()
					this.$message.success("停止成功")
				}else{
					this.$alert(res.message, "提示", {type: 'error'})
				}
				loading.close();
			},
			//表格选择后回调事件
			selectionChange(selection){
				this.selection = selection;
			},
			//表格内开关
			changeSwitch(val, row){
				row.status = row.status == '1'?'0':'1'
				row.$switch_status = true;
				setTimeout(()=>{
					delete row.$switch_status;
					row.status = val;
					this.$message.success("操作成功")
				}, 500)
			},
			searchGroup(row) {
				this.search.groupName = row.groupName;
				this.$refs.table.upData(this.search)
			},
			//搜索
			upsearch(){
				this.$refs.table.upData(this.search)
			},
			upclear(){
				for(var n in this.search)
				    this.search[n]=''
				this.$refs.table.upData(this.search)
			},
			//本地更新数据
			handleSaveSuccess(data, mode){
				if(mode=='add'){
					this.$refs.table.refresh()
				}else if(mode=='edit'){
					this.$refs.table.refresh()
				}
			},
			//本地更新数据
			runSaveSuccess(){
				this.$refs.table.refresh()
			}
		}
	}
</script>

<style scoped>
.scheduleList {
	line-height: 1.75em;
}
.scheduleListItem {
	min-width: 200px;
    display: inline-block;
    margin-right: 2em;
}
</style>
